package org.argus.common.web.core.exception;

/**
 * 全局异常处理器
 * @Author 刘文/Cliff Liu
 * @Date 2025/1/12
 */
import lombok.extern.slf4j.Slf4j;
import org.argus.common.core.domain.R;
import org.argus.common.core.exception.ServiceException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 业务异常，统一归类到 400 状态码
     * @param ex
     * @return
     */
    @ExceptionHandler(value = ServiceException.class)
    @ResponseStatus(HttpStatus.OK)
    public @ResponseBody R<Void> handleException(ServiceException ex) {
        return R.fail(ex.getCode() == null ? HttpStatus.BAD_REQUEST.value() : ex.getCode().intValue(), ex.getMessage());
    }

    @ExceptionHandler(value = Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public @ResponseBody R<Void> handleException(Exception ex) {
        log.error("未处理异常", ex);
        return R.fail(HttpStatus.INTERNAL_SERVER_ERROR.value(), ex.getMessage());
    }
}